<?php
/**
 * The View Template Engine
 * 为了实现规范和编码标准化，如果有用到smarty的函数，需要重写的就重写
 * 
 * @package SView
 * @author Shuky
 * @since v1.0
 * @version $Id: View.php 82 2010-12-23 18:23:35Z shukyoo@gmail.com $
 */
namespace SView;


class View
{
    // 自身实例
    protected static $_instance = null;
    
    // 事件集合
    protected $_events = array();
    
    // 模板变量托管
    protected $_variables = array();
    
    // 模板路径
    protected $_viewPath;
    
    // 缓存路径
    protected $_cachePath;
    
    
    /**
     * 单件模式，自身获取实例
     */
    public static function getInstance()
    {
		if (null === self::$_instance) {
			self::$_instance = new self();
		}
		return self::$_instance;
    }


	/**
	 * 获取模板文件路径
	 */
	public function getViewFile($file)
	{
		$filePath = $this->getViewPath() .'/'. $file;
		if (!is_file($filePath)) {
			throw new ViewException('模板文件"'. $file .'"不存在');	
		}
		return $filePath;
	}


    /**
     * 调用显示模板
     * @param string $template
     */
    public function render($template)
    {
        $reCache = 0;
		$viewFile = $this->getViewFile($template);
        $cacheFile = $this->getCachePath() .'/'. $template;
        
        if (!is_file($cacheFile) || filemtime($viewFile) > filemtime($cacheFile)) {
        	$reCache = 1;
        }
        if ($reCache == 1) {
            // 编译处理
            $compile = new Compile($this);
        	$compile->process($viewFile, $cacheFile);
        }
        ob_start();
    	include $cacheFile;
    	$content = ob_get_contents();
    	ob_end_clean();
    	echo $content;
    }

    
    /**
     * 传入模板值
     */
    public function __set($key, $value)
    {
    	$this->_variables[$key] = $value;
    }
    
    
    /**
     * 获取模板值
     */
    public function __get($key)
    {
    	return isset($this->_variables[$key]) ? $this->_variables[$key] : null;
    }


    /**
     * set && get
	 * ViewPath
     */
    public function setViewPath($path)
    {
    	$this->_viewPath = $path;
    }
    public function getViewPath()
    {
    	return rtrim($this->_viewPath, '/');
    }

    /**
     * set && get
	 * CachePath
     */
    public function setCachePath($path)
    {
    	$this->_cachePath = $path;
    }
    public function getCachePath()
    {
    	return rtrim($this->_cachePath, '/');
    }
}